﻿using MgSoft.Excel.Model.Dto;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Reflection;
using System.Security.Permissions;
using System.Text;

namespace MgSoft.Excel.Model.Excel
{
    [Serializable]
    public class MgRow
    {
        public MgRow() { }
        public MgRow(List<MgCell> mgCells,int rowIndex)
        {
            MgCells = mgCells;
            RowIndex = rowIndex;
        }

        public int RowIndex { get; set; }

        public List<MgCell> MgCells { get; private set; }

        public MgCell GetCell(int columnIndex)
        {
            return MgCells.Where(p => p.ColumnIndex == columnIndex).SingleOrDefault();
        }

        public MgCell GetCell(string columnName)
        {
            return MgCells.Where(p => p.ColumnName == columnName).SingleOrDefault();
        }

        public T ToObject<T>() where T: IExcelDto,new()
        {
            var tType = new T().GetType();
            T t = new T();
            foreach (PropertyInfo propertie in tType.GetProperties())
            {
                var cell = this.GetCell(propertie.Name);
                try
                {
                    propertie.SetValue(t, cell?.Value);
                }
                catch (Exception e)
                {
                    throw new MgExcelException(RowIndex,cell.ColumnIndex,$"类型转换异常,值为{cell?.Value}",e);
                }
            }

            t.SetRow(this);

            return t;
        }
    }
}
